import os.path
import csv


class DataOutput:
    def __init__(self,data_dir):
        self.city_name = ""
        self.spot_name = ""
        self.data_dir = data_dir

    def makeDir(self):
        self.dir = f"./{self.data_dir}/{self.city_name}/{self.spot_name}/"
        if not os.path.exists(self.dir):
            os.makedirs(self.dir)

    def write_comment(self,contents):
        self.makeDir()
        with open(self.dir + "comment.txt", mode="a", encoding="utf-8") as f:
            for c in contents:
                f.write(c)

    def merge_comment(self):
        for cityName in os.listdir(self.data_dir):
            city_dir = f"{self.data_dir}/{cityName}"
            comment = ""
            for spot_name in os.listdir(city_dir):
                if spot_name == "comment.txt":
                    continue
                spot_dir = f"{city_dir}/{spot_name}"
                target_file = f"{spot_dir}/comment.txt"
                with open(target_file, mode="r", encoding="utf-8") as f:
                    comment += f.read()

            with open(f"{city_dir}/comment.txt", mode="a", encoding="utf-8") as f:
                f.write(comment)

    def write_region(self,regions):
        self.makeDir()
        headers = ['region', 'count']
        with open(self.dir + "region.csv", 'w', newline='', encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerow(headers)
            for r in regions:
                writer.writerow(r)
